package com.service;
/**
 * @author harry
 * @version 1.0
 * 邮件服务
 * 支持以下四种类型邮件：1.简单文本  2.简单HTML文本（无资源引用）  3.带附件  4.复杂HTML（有资源引用）
 * 除了第一种是纯文本，其他三种邮件的文本格式都为HTML
 *
 * 发送方邮箱需开启POP3/SMTP/IMAP服务
 * 以SMTP为例，配置文件需指定以下项：
 *  spring.mail.host=smtp.163.com # 邮箱配置
 *  spring.mail.username=harry@163.com # 邮箱地址
 *  spring.mail.password=ABCDEFGHIJKLMN # SMTP授权码
 *  spring.mail.port=25
 *  spring.mail.protocol=smtp
 *  spring.mail.default-encoding=UTF-8
 */


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class MailService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 从配置文件获取发送方邮箱地址
     */
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 简单文本邮件
     * @param to 接收者邮箱地址，如：harry@163.com
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    @Async
    public void sendSimpleMail(String to, String subject, String content){

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        message.setFrom(from);

        mailSender.send(message);
    }

    /**
     * 简单HTML文本邮件
     * @param to 接收者邮箱地址
     * @param subject 邮件主题
     * @param content HTML内容
     * @throws MessagingException
     */
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        helper.setFrom(from);

        mailSender.send(message);
    }

    /**
     * 带有附件的HTML邮件
     * @param to 接收者邮箱地址
     * @param subject 邮件主题
     * @param content HTML文本内容
     * @param filePath 附件文件路径
     * @throws MessagingException
     */
    public void sendAttachmentsMail(String to, String subject, String content,
                                    String filePath) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        helper.setFrom(from);

        FileSystemResource file = new FileSystemResource(new File(filePath));
        String fileName = file.getFilename();
        helper.addAttachment(fileName, file);

        mailSender.send(message);
    }

    /**
     * 有资源引用的邮件（如插入图片）
     * @param to 接收者邮箱地址
     * @param subject 邮件主题
     * @param content HTML内容
     * @param rscPath 资源路径
     * @param rscId 资源ID，自定义
     * @throws MessagingException
     */
    public void sendInlineResourceMail(String to, String subject, String content,
                                       String rscPath, String rscId) {
        logger.info("发送InlineResource邮件开始: {},{},{},{},{}", to, subject, content, rscPath, rscId);

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;

        try {

            helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setFrom(from);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);
            mailSender.send(message);
            logger.info("发送InlineResource邮件成功!");

        } catch (MessagingException e) {
            logger.info("发送InlineResource邮件失败: ", e);
        }

    }
}
